
package http.file.index;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedFile;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SystemPropertyUtil;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_0;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class HttpFileIndexServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    public static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
    public static final String HTTP_DATE_GMT_TIMEZONE = "GMT";
    public static final int HTTP_CACHE_SECONDS = 60;
    private FullHttpRequest request;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        this.request = request;
        //判断http解码是否成功
        if (!request.decoderResult().isSuccess()) {
            sendError(ctx, BAD_REQUEST,"请求失败");
            return;
        }
        //必须是get方法
        if (!GET.equals(request.method())) {
            sendError(ctx, METHOD_NOT_ALLOWED,"只支持"+GET.name()+"方法");
            return;
        }
        final boolean keepAlive = HttpUtil.isKeepAlive(request);
        final String uri = request.uri();//获取request的url,这里获取的相对路径
        final String path = urlToLocalPath(uri);
        if (path == null) {
            sendError(ctx, FORBIDDEN,"路径错误");
            return;
        }

        File file = new File(path);
        if (file.isHidden() || !file.exists()) {
            sendError(ctx, NOT_FOUND,"文件不存在");
            return;
        }

        if (file.isDirectory()) {
            if (uri.endsWith("/")) {//展示目录下所有索引文件
                sendListing(ctx, file, uri);
            } else {
                sendRedirect(ctx, uri + '/');//重定向到目录文件，展示目录下所有索引文件
            }
            return;
        }

        if (!file.isFile()) {
            sendError(ctx, FORBIDDEN,"请求的不是一个文件");
            return;
        }

        //If-Modified-Since是标准的HTTP请求头标签，
        // 在发送HTTP请求时，把浏览器端缓存页面的最后修改时间一起发到服务器去，服务器会把这个时间与服务器上实际文件的最后修改时间进行比较
        String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE);
        //判断浏览器是否启用缓存
        if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
            //获取浏览器缓存文件的最后修改日期
            SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.getDefault());
            Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
            long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
            long fileLastModifiedSeconds = file.lastModified() / 1000;
            //文件的修改日期和获取浏览器缓存文件的最后修改日期比较
            if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {//如果一样表示浏览器已经缓存过文件，服务器不再发送
                sendNotModified(ctx);
                return;
            }
        }
        //走到说明要发送文件给浏览器了
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
        } catch (FileNotFoundException ignore) {
            sendError(ctx, NOT_FOUND,"文件不存在");
            return;
        }
        long fileLength = raf.length();//文件长度

        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        HttpUtil.setContentLength(response, fileLength);
        //设置reponse的content-type:文件后缀名称
        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.getDefault());
        dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
        //设置reponse的Cache-Control和Expires
        /**
         * Cache-Control: cache-directive
         * cache-directive可以为以下：
         * request时用到：
         * | "no-cache"
         * | "no-store"
         * | "max-age" "=" delta-seconds
         * | "max-stale" [ "=" delta-seconds ]
         * | "min-fresh" "=" delta-seconds
         * | "no-transform"
         * | "only-if-cached"
         * | "cache-extension"
         * response时用到：
         * | "public"
         * | "private" [ "=" <"> field-name <"> ]
         * | "no-cache" [ "=" <"> field-name <"> ]
         * | "no-store"
         * | "no-transform"
         * | "must-revalidate"
         * | "proxy-revalidate"
         * | "max-age" "=" delta-seconds
         * | "s-maxage" "=" delta-seconds
         * | "cache-extension"
         Public  指示响应可被任何缓存区缓存。
         Private  指示对于单个用户的整个或部分响应消息，不能被共享缓存处理。这允许服务器仅仅描述当用户的
         部分响应消息，此响应消息对于其他用户的请求无效。
         no-cache  指示请求或响应消息不能缓存（HTTP/1.0用Pragma的no-cache替换）
         根据什么能被缓存
         no-store  用于防止重要的信息被无意的发布。在请求消息中发送将使得请求和响应消息都不使用缓存。
         根据缓存超时
         max-age  指示客户机可以接收生存期不大于指定时间（以秒为单位）的响应。
         min-fresh  指示客户机可以接收响应时间小于当前时间加上指定时间的响应。
         max-stale  指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值，那么客户机可以
         接收超出超时期指定值之内的响应消息。
         Expires 表示存在时间，允许客户端在这个时间之前不去检查（发请求），等同max-age的
         效果。但是如果同时存在，则被Cache-Control的max-age覆盖。
         格式：
         Expires = "Expires" ":" HTTP-date
         例如
         Expires: Thu, 01 Dec 1994 16:00:00 GMT （必须是GMT格式）
         * **/
        Calendar time = new GregorianCalendar();
        response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));
        time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
        response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime()));
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
        response.headers().set(
                HttpHeaderNames.LAST_MODIFIED, dateFormatter.format(new Date(file.lastModified())));
        //设置reponse的connection:close或connection:keep-alive
        if (!keepAlive) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        } else if (request.protocolVersion().equals(HTTP_1_0)) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        //向浏览器发送头部消息
        ctx.write(response);
        //发送文件
        ChannelFuture sendFileFuture;
        ChannelFuture lastContentFuture;
        sendFileFuture =
                ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
        //手动发送结束表示
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

        sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
                if (total < 0) { // total unknown
                    System.err.println(future.channel() + "数据传输进度" + progress);
                } else {
                    System.err.println(future.channel() + "数据传输进度 " + progress + " / " + total);
                }
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture future) {
                System.err.println(future.channel() + " 数据结束.");
            }
        });
        //根据是否长连接判断是否要关闭浏览器和服务器建立的连接
        if (!keepAlive) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendError(ctx, INTERNAL_SERVER_ERROR,cause.getMessage());
        }
    }
    private static String urlToLocalPath(String uri) {
        try {
            uri = URLDecoder.decode(uri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }

        if (uri.isEmpty() || uri.charAt(0) != '/') {
            return null;
        }
        //本地分割符号替换url中的 '/'
        uri = uri.replace('/', File.separatorChar);
        // 返回文件的本地绝对路径
        return SystemPropertyUtil.get("user.dir") + File.separator + uri;
    }

    private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[^-\\._]?[^<>&\\\"]*");

    private void sendListing(ChannelHandlerContext ctx, File dir, String dirPath) {
        StringBuilder buf = new StringBuilder()
                .append("<!DOCTYPE html>\r\n")
                .append("<html><head><meta charset='utf-8' /><title>")
                .append("列表: ")
                .append(dirPath)
                .append("</title></head><body>\r\n")

                .append("<h3>Listing of: ")
                .append(dirPath)
                .append("</h3>\r\n")

                .append("<ul>")
                .append("<li><a href=\"../\">..</a></li>\r\n");

        File[] files = dir.listFiles();
        if (files != null) {
            for (File f: files) {
                if (f.isHidden() || !f.canRead()) {
                    continue;
                }

                String name = f.getName();
                if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
                    continue;
                }

                buf.append("<li><a href=\"")
                        .append(name)
                        .append("\">")
                        .append(name)
                        .append("</a></li>\r\n");
            }
        }

        buf.append("</ul></body></html>\r\n");

        ByteBuf buffer = ctx.alloc().buffer(buf.length());
        buffer.writeCharSequence(buf.toString(), CharsetUtil.UTF_8);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");

        replayMessage(ctx, response);
    }

    private void sendRedirect(ChannelHandlerContext ctx, String newUri) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND, Unpooled.EMPTY_BUFFER);
        /**
         location该属性表示该网页的跳转网址，也被称为重定向网址
         * **/
        response.headers().set(HttpHeaderNames.LOCATION, newUri);
        replayMessage(ctx, response);
    }

    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status,String errMessage) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, status, Unpooled.copiedBuffer(errMessage+":" + status + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        replayMessage(ctx, response);
    }


    private void sendNotModified(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED, Unpooled.EMPTY_BUFFER);
        setDateHeader(response);
        replayMessage(ctx, response);
    }

    private void replayMessage(ChannelHandlerContext ctx, FullHttpResponse response) {
        final FullHttpRequest request = this.request;
        final boolean keepAlive = HttpUtil.isKeepAlive(request);//判断是否是长链接
        HttpUtil.setContentLength(response, response.content().readableBytes());
        if (!keepAlive) {
            //不是长链接返回头设置：connection:close
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        } else if (request.protocolVersion().equals(HTTP_1_0)) {
            //长链接返回头设置：connection:keep-alive
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        //向客户端推送消息
        ChannelFuture flushPromise = ctx.writeAndFlush(response);
        if (!keepAlive) {
            //不是长链接，设置关闭监听器，返回给客户端信息结束后关闭连接
            flushPromise.addListener(ChannelFutureListener.CLOSE);
        }
    }

    private static void setDateHeader(FullHttpResponse response) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.getDefault());
        dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

        Calendar time = new GregorianCalendar();
        response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));
    }

}
